﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace WoWTimer.Classes
{
    public static class OptionsReadWrite
    {
        public static Options Load(string filename)
        {
            Options o = new Options();
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                XmlNodeList test = doc.GetElementsByTagName("config")[0].ChildNodes;
                foreach (XmlNode node in test)
                {
                    if (node.Name == "luadir")
                        o.LuaDir = node.InnerText;
                    else if (node.Name == "luafile")
                        o.LuaFile = node.InnerText;
                    else if (node.Name == "remaining")
                        o.Remaining = Int32.Parse(node.InnerText);
                    else if (node.Name == "volume")
                        o.Volume = Int32.Parse(node.InnerText);
                    else if (node.Name == "text")
                        o.SpeachText = node.InnerText;
                }
            }
            catch
            {
            }

            return o;
        }

        public static void Save(string filename, Options o)
        {
            // check for null references
            if (filename == null)
                return;
            if (o == null)
                return;

            // write the new settings to the config file
            XmlDocument doc = new XmlDocument();
            XmlNode myRoot, myNode;

            // create root and append
            myRoot = doc.CreateElement("config");
            doc.AppendChild(myRoot);

            // create luadir node and append
            myNode = doc.CreateElement("luadir");
            myNode.InnerText = o.LuaDir;
            myRoot.AppendChild(myNode);

            // create luadir node and append
            myNode = doc.CreateElement("luafile");
            myNode.InnerText = o.LuaFile;
            myRoot.AppendChild(myNode);

            // create remaining time node and append
            myNode = doc.CreateElement("remaining");
            myNode.InnerText = o.Remaining.ToString();
            myRoot.AppendChild(myNode);

            // create volume node and append
            myNode = doc.CreateElement("volume");
            myNode.InnerText = o.Volume.ToString();
            myRoot.AppendChild(myNode);

            // create speech text node and append
            myNode = doc.CreateElement("text");
            myNode.InnerText = o.SpeachText;
            myRoot.AppendChild(myNode);

            // save the config file
            doc.Save(filename);
        }
    }
}
